package hai.wom.org.qyer_home.utils;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import hai.wom.org.qyer_home.callback.ICallback;


/**
 * Created by Administrator on 2016/12/24.
 */
public class HttpUtils extends AsyncTask<String, Void, byte[]> {
    private ICallback callbck;

    public HttpUtils(ICallback callbck) {
        this.callbck = callbck;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((len = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                    baos.flush();
                }
                return baos.toByteArray();

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        if (bytes != null) {
            callbck.getData(new String(bytes));
        }
    }
}
